#include "BaseConfig.pb.h"
#include "ProtobufTextFormatter.h"

#include <glog/logging.h>
#include <google/protobuf/text_format.h>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
using namespace std;

std::string bytes2hexstr(const unsigned char *buf, unsigned int len)
{
    if (buf == nullptr)
        return "";

    std::ostringstream oss;
    oss << std::hex << std::setfill('0');
    for (int i = 0; i < len; i++) {
        oss << std::setw(2) << static_cast<unsigned int>(buf[i]);
        if (i != len - 1)
            oss << ' ';
    }
    oss << std::oct;
    return oss.str();
}

void write_proto()
{
    std::map<int32_t, std::string> map_strings;
    map_strings[0] = "hello, world!";
    map_strings[1] = "how you doing!";

    foo::bar::BaseConfig conf;
    conf.set_database_ip("127.0.0.1");
    conf.set_database_port(3306);
    conf.set_database_username("admin");
    conf.set_database_password("password");
    conf.set_double_value(1.23456789);
    for (int i = 0; i < 4; i++) {
        auto station = conf.add_stationlist();
        station->set_station_id(to_string(i + 1));
    }
    conf.mutable_map_string()->insert(map_strings.begin(), map_strings.end());
    conf.mutable_map_string()->insert(google::protobuf::MapPair<int32_t, std::string>(2, "what's up man?!"));

    const char bytes_data[] = {0x01, 0x02, 0x03, 0x04};
    conf.set_bytes_data(bytes_data, sizeof(bytes_data));
    protobuf_write_to_file(conf, "./base_config.conf");
}

void read_proto()
{
    foo::bar::BaseConfig conf;
    protobuf_read_from_file(conf, "./base_config.conf");
    LOG(INFO) << "ip      : " << conf.database_ip();
    LOG(INFO) << "port    : " << conf.database_port();
    LOG(INFO) << "username: " << conf.database_username();
    LOG(INFO) << "password: " << conf.database_password();
    LOG(INFO) << "value   : " << conf.double_value();
    LOG(INFO) << "sta size: " << conf.stationlist_size();

    std::map<int32_t, std::string> map_strings;
    map_strings.insert(conf.map_string().begin(), conf.map_string().end());
    for (auto iter = map_strings.begin(); iter != map_strings.end(); iter++) {
        LOG(INFO) << "map strs: " << iter->first << " - " << iter->second;
    }

    std::string message = bytes2hexstr((unsigned char *)conf.bytes_data().c_str(), conf.bytes_data().size());
    LOG(INFO) << "message : " << message;
}

int main(int argc, char *argv[])
{
    write_proto();
    read_proto();
    return 0;
}